package top.hcode.hoj.dao.collect;

import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.hcode.hoj.common.LazyDao;
import top.hcode.hoj.mapper.ItechCollectionMapper;
import top.hcode.hoj.pojo.entity.coll.ItechCollection;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author orangej
 * @since 2025-01-21
 */
@Service
@RequiredArgsConstructor
public class ItechCollDao extends ServiceImpl<ItechCollectionMapper, ItechCollection> {

    private final LazyDao dao;

    @Cached(cacheType = CacheType.BOTH)
    public int getExamMinutes(String collId) {
        ItechCollection coll = lambdaQuery().select(ItechCollection::getExamMinutes)
                .eq(ItechCollection::getId, collId)
                .one();
        if (coll == null) {
            throw new IllegalArgumentException("未知的活动 : " + collId);
        } else {
            return coll.getExamMinutes();
        }
    }

    @Cached(cacheType = CacheType.BOTH)
    public ItechCollection getByIdCache(String collId) {
        return lambdaQuery()
                .eq(ItechCollection::getId, collId)
                .one();
    }

    @Cached(cacheType = CacheType.BOTH)
    public List<ItechCollection> queryListBySchoolAndGrade(String schoolId, Integer grade) {
        return dao.selectList(ItechCollection.class, "select * from itech_collection where " +
                "school_list like ? and find_in_set(?, grade_list) != 0 and enabled = 1", schoolId, grade);
    }

    public Map<String, String> queryIdTitleMap(List<String> collIdList) {
        return lambdaQuery().select(ItechCollection::getId, ItechCollection::getCollTitle)
                .in(ItechCollection::getId, new HashSet<>(collIdList))
                .list().stream().collect(Collectors.toMap(ItechCollection::getId, ItechCollection::getCollTitle));
    }
}